package datasource

import (
	"baize/app/setting"
	"context"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/wire"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var SysDatabase = "sys_baize"
var Collection map[string]string

func init() {
	Collection = make(map[string]string)
	Collection["user"] = "sys_user"
	Collection["menu"] = "sys_menu"
	Collection["loginInfo"] = "sys_loginInfo"
	Collection["role"] = "role"
	Collection["deptType"] = "sys_dept_type"
	Collection["deptData"] = "sys_dept_data"
}

// ProviderSet is datasource providers.
var ProviderSet = wire.NewSet(NewData)

// NewData .
func NewData(m *setting.Mongo) (*mongo.Client, func(), error) {
	ctx := context.Background()
	// 创建客户端
	masterOpt := options.Client().ApplyURI(m.Uri)
	masterOpt.SetMaxPoolSize(m.MaxPoolSize)
	masterOpt.SetMinPoolSize(m.MinPoolSize)
	client, err := mongo.Connect(ctx, masterOpt)
	return client, nil, err
}

type MongoQueryEntity interface {
	GetMongoLimit() *options.FindOptions
	GetSize() int64
	GetOffset() int64
}

func MongoQueryListAndTotal[T any](ctx context.Context, collection *mongo.Collection, t []*T, filter interface{}, mqe MongoQueryEntity, opts ...*options.FindOptions) (list []*T, total int64) {
	total, err := collection.CountDocuments(ctx, filter)
	if err != nil {
		panic(err)
	}
	list = make([]*T, 0, mqe.GetSize())
	if total > mqe.GetOffset() {
		cur, err := collection.Find(ctx, filter, append([]*options.FindOptions{mqe.GetMongoLimit()}, opts...)...)
		if err != nil {
			panic(err)
		}
		defer cur.Close(ctx)
		err = cur.All(ctx, &list)
		if err != nil {
			panic(err)
		}
	}
	return
}
